package com.sctvcloud.qingchuan.ui.activities;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Pair;
import android.view.View;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.gridsum.tracker.GridsumWebDissector;
import com.huaqiyun.datacollect.collect.DataCollectRequest;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.sctvcloud.qingchuan.R;
import com.sctvcloud.qingchuan.application.Cache;
import com.sctvcloud.qingchuan.application.Constances;
import com.sctvcloud.qingchuan.base.BaseAccountActivity;
import com.sctvcloud.qingchuan.beans.AccountBean;
import com.sctvcloud.qingchuan.beans.AccountNewsArticleBean;
import com.sctvcloud.qingchuan.beans.AccountNewsDetail;
import com.sctvcloud.qingchuan.http.AbsNetCallBack;
import com.sctvcloud.qingchuan.http.NetUtils;
import com.sctvcloud.qingchuan.ui.dialog.ShareFragment;
import com.sctvcloud.qingchuan.ui.utils.DataUtils;
import com.sctvcloud.qingchuan.ui.utils.GlideCircleTransform;
import com.sctvcloud.qingchuan.ui.utils.GlideUtil;
import com.sctvcloud.qingchuan.utils.UserManager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.RequestBody;

/**
 * 公众号文章详情
 */
public class AccountNewsDetailActivity extends BaseAccountActivity {
    @BindView(R.id.account_news_title)
    protected CustomFontTextView accountNewsTitle;
    @BindView(R.id.account_layout)
    protected RelativeLayout account_layout;
    @BindView(R.id.account_avatar)
    protected ImageView accountAvatar;
    @BindView(R.id.account_name)
    protected CustomFontTextView accountName;
    @BindView(R.id.account_time)
    protected CustomFontTextView accountTime;
    @BindView(R.id.account_subscribe)
    protected ImageView accountSubscribe;
    @BindView(R.id.account_news_content)
    protected WebView accountNewsContent;
    public static final String NEWS_ID = "news_id";
    private long newsId;
    private AccountNewsDetail newsDetail;
    private AccountBean mAccountDetailBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getDetailData();
    }

    @Override
    protected void initInject() {
        setContentView(R.layout.activity_account_news_detail);
        ButterKnife.bind(this);
    }

    private void getDetailData() {
        newsId = getIntent().getLongExtra(NEWS_ID, 0);
        if (newsId > 0) {
            String accountToken = "";
            if (null != UserManager.getInstance().getUser() && null != UserManager.getInstance().getUser().getAccountUser()) {
                accountToken = UserManager.getInstance().getUser().getAccountUser().getAccess_token();
            }
            Map<String, String> formMaildata = new HashMap<>();
            formMaildata.put("articleId", "" + newsId);
            Map<String, RequestBody> bodyMap = DataUtils.generateRequestBody(formMaildata);
            showProgress("正在加载...");
            NetUtils.getNetAdapter().getNewsItemString(getOwnerName(), accountToken, bodyMap, new AbsNetCallBack<String>(String.class) {
                @Override
                public void onSucStr(String news) {
                    if (!TextUtils.isEmpty(news)) {
                        try {
                            newsDetail = gson.fromJson(news, AccountNewsDetail.class);
                            if (newsDetail != null) {
                                initDetailData(newsDetail);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        onError(null, "数据异常");
                    }
                }

                @Override
                public void onError(Throwable ex, String errorMsg) {
                    toast(errorMsg);
                }

                @Override
                public void onEnd() {
                    closeProgress();
                }
            });

        }
    }

    /**
     * 请求公众号详情数据
     */
    private void getAccountDetail(String accointId) {
        String accessToken = "";
        if (null != UserManager.getInstance().getUser() && null != UserManager.getInstance().getUser().getAccountUser()) {
            accessToken = UserManager.getInstance().getUser().getAccountUser().getAccess_token();
        }
        Map<String, String> formMaildata = new HashMap<>();
        formMaildata.put("tenantId", Constances.TENANT_ID);
        formMaildata.put("hisUserId", accointId);

        Map<String, RequestBody> bodyMap = DataUtils.generateRequestBody(formMaildata);
        showProgress("正在加载...");
        NetUtils.getNetAdapter().getAccountInfoString(getOwnerName(), accessToken, bodyMap, new AbsNetCallBack<String>(String.class) {
            @Override
            public void onSucStr(String news) {
                if (!TextUtils.isEmpty(news)) {
                    try {
                        mAccountDetailBean = gson.fromJson(news, AccountBean.class);
                        if (mAccountDetailBean != null) {
                            initAuthorData(mAccountDetailBean);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    onError(null, "数据异常");
                }
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                toast(errorMsg);
            }

            @Override
            public void onEnd() {
                closeProgress();
            }
        });


    }

    private void initDetailData(AccountNewsDetail bean) {
        AccountNewsArticleBean article = bean.getArticle();
        if (null != article) {
            getAccountDetail(bean.getArticle().getAuthorId());
            account_layout.setVisibility(View.VISIBLE);

            accountNewsTitle.setText(article.getTitle());
//            accountName.setText(article.getTitle());
//            String timeStr = DateUtils.formatDate(DateUtils.getDataDate(newsItem), "");
//            accountTime.setText(timeStr);
//            accountNewsContent.setText(newsItem.getContent());
            accountNewsContent.loadDataWithBaseURL(null, article.getContent(), "text/html", "UTF-8", null);
        }
    }

    private void initAuthorData(AccountBean bean) {
        if (null != bean) {
            GlideUtil.getDynamicGlid(this, bean.getUserImage(), true).diskCacheStrategy(DiskCacheStrategy.NONE)
                    .transform(new GlideCircleTransform(this)).into(accountAvatar);
            accountName.setText(bean.getUserNickName());
            accountTime.setVisibility(View.GONE);
//            String timeStr = DateUtils.formatDate(DateUtils.getDataDate(newsItem), "");
//            accountTime.setText(timeStr);
            if (bean.isHasAttention()) {
                accountSubscribe.setImageDrawable(getResources().getDrawable(R.mipmap.icon_subscribed));
            } else {
                accountSubscribe.setImageDrawable(getResources().getDrawable(R.mipmap.icon_subscribe));
            }
        }
    }

    @OnClick(value = {R.id.account_detail_back, R.id.account_subscribe,R.id.title_top_share})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.account_detail_back:
                onBackPressed();
                break;
            case R.id.account_subscribe:
                //TODO 关注、取消关注
                if (null != mAccountDetailBean) {
                    if (null != UserManager.getInstance().getUser() && null != UserManager.getInstance().getUser().getAccountUser()) {
                        setResult(RESULT_OK);
                        toAttentionClick(mAccountDetailBean.isHasAttention());
                    } else {
                        toLogin();
                    }
                }
                break;
            case R.id.title_top_share:
                if (!TextUtils.isEmpty(newsDetail.getPreViewPath())) {
                    showShareFragment(newsDetail, new ShareFragment.OnShareFragmentClickListener() {
                        @Override
                        public void onClick(Pair<String, String> pair) {

                        }
                    });
                } else {
                    toast(R.string.share_data_wrong);
                }


                break;

        }
    }

    /**
     * 处理 关注或取消关注
     *
     * @param isAttention
     */
    private void toAttentionClick(boolean isAttention) {
        if (isAttention) {
            toUnAttentionAccount(mAccountDetailBean.getUserId(), new OnAttentionListener() {
                @Override
                public void OnAttention(boolean isSuccess, long attentionedUserNums) {

                }

                @Override
                public void OnUnAttention(boolean isSuccess, long attentionedUserNums) {
                    mAccountDetailBean.setHasAttention(!mAccountDetailBean.isHasAttention());
                    if (mAccountDetailBean.isHasAttention()) {
                        accountSubscribe.setImageDrawable(getResources().getDrawable(R.mipmap.icon_subscribed));
                    } else {
                        accountSubscribe.setImageDrawable(getResources().getDrawable(R.mipmap.icon_subscribe));
                    }
                }
            });
        } else {
            toAttentionAccount(mAccountDetailBean.getUserId(), new OnAttentionListener() {
                @Override
                public void OnAttention(boolean isSuccess, long attentionedUserNums) {
                    mAccountDetailBean.setHasAttention(!mAccountDetailBean.isHasAttention());
                    if (mAccountDetailBean.isHasAttention()) {
                        accountSubscribe.setImageDrawable(getResources().getDrawable(R.mipmap.icon_subscribed));
                    } else {
                        accountSubscribe.setImageDrawable(getResources().getDrawable(R.mipmap.icon_subscribe));
                    }
                }

                @Override
                public void OnUnAttention(boolean isSuccess, long attentionedUserNums) {

                }
            });
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == CODE_REQUEST_LOGIN) {
                if (null != newsDetail) {
                    AccountNewsArticleBean article = newsDetail.getArticle();
                    if (null != article) {
                        getAccountDetail(newsDetail.getArticle().getAuthorId());
                        setResult(RESULT_OK);
                    }
                }
            }
        }
    }
}
